﻿#include <QTcpSocket>
#include <QDateTime>
#include "CIsapiServer.h"
#include "CGlobal.h"

CIsapiServer::CIsapiServer()
{

}

CIsapiServer::~CIsapiServer()
{

}

void CIsapiServer::setNetworkParameter(QString sIp, int nPort)
{
	m_sIp = sIp;
	m_nPort = nPort;
}

bool CIsapiServer::startServer(QString &sErrMsg)
{
	if (!this->listen(QHostAddress("0.0.0.0"), m_nPort))
	{
		sErrMsg = A2T("开启监听失败");
		return false;
	}
	else
	{
		return true;
	}
}

void CIsapiServer::incomingConnection(qintptr socketDescriptor)
{
	// 当有新的连接时，创建一个套接字来处理它
	QTcpSocket *socket = new QTcpSocket(this);
	socket->setSocketDescriptor(socketDescriptor);

	connect(socket, &QTcpSocket::readyRead, this, &CIsapiServer::onReadyRead);
	connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
}

void CIsapiServer::onReadyRead()
{
	QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
	if (!socket) return;

	// 读取请求数据
	QByteArray requestData = socket->readAll();
	QString srequestData = QString::fromUtf8(requestData);
	qDebug() << A2T("请求数据: ") << srequestData;
	emit(sigNewRequest(requestData));
	//默认返回一个处理成功相应
	QByteArray responseHeader = "HTTP/1.1 200 OK\r\n" +
		QString("Date: %1\r\n").arg(QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss")).toUtf8() +
		QString("Connection: close\r\n\r\n").toUtf8();
	socket->write(responseHeader);
	socket->flush();
	// 关闭连接
	socket->disconnectFromHost();
}
